package com.gzmu.myprint.controller;

import com.alibaba.fastjson.JSONObject;
import com.gzmu.myprint.mapper.ArtMapper;
import com.gzmu.myprint.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ArtController {
    @Autowired
    private ArtMapper artMapper;

    @ResponseBody
    @RequestMapping(value = "/checkUser", produces = "application/json;charset=UTF-8")
    public Object checkUser(HttpServletRequest request) {
        String groupId = request.getParameter("groupId");
        String serialNum = request.getParameter("serialNum");
        String username = request.getParameter("username");
        String checkcode = request.getParameter("checkcode");
        System.out.println("groupId:" + groupId + ",serialNum:" + serialNum + ",username:" + username + ",checkcode:" + checkcode);
        Recorder recorder = new Recorder();
        recorder.setGroud(Integer.valueOf(groupId));
        recorder.setSerial(Integer.valueOf(serialNum));
        String reslut = artMapper.SelectRecorder(recorder);
        User user = new User();
        user.setName(username);
        user.setGroup(Integer.valueOf(groupId));
        user.setSerial(Integer.valueOf(serialNum));
        artMapper.login(user);
        System.out.println("uid:" + user.getUid());
        Map map = new HashMap();
        if (reslut != null && reslut.equals(checkcode)) map.put("ok", true);
        else map.put("ok", false);

        map.put("userId", user.getUid());
        return JSONObject.toJSON(map);
    }

    @ResponseBody
    @RequestMapping(value = "/logout", produces = "application/json;charset=UTF-8")
    public String logout(HttpServletRequest request) {
        String uid = request.getParameter("userId");
        artMapper.logout(Integer.valueOf(uid));
        return "success";
    }

    @ResponseBody
    @RequestMapping(value = "/choiceMajor", produces = "application/json;charset=UTF-8")
    public Object choiceMajor(HttpServletRequest request) {
        String codeStr = request.getParameter("codeStr");
        String uid = request.getParameter("uid");
        if (artMapper.SelectSubjectsState().equals( "0" )){
            System.out.println("enteringScore:");//录入
            return enteringScore(codeStr, uid);
        }else{
            System.out.println("reviewScore:");//复核
            return reviewScore(codeStr);
        }
    }

    public Object enteringScore(String codeStr, String uid){
        System.out.println("codeStr:" + codeStr + ",uid:" + uid);
        Map <String, Object> map = new HashMap <>();
        //查询所属专业
        String subjects = artMapper.SelectSubjects(codeStr);
        //查询学生信息
        Student student = artMapper.selectStudentByRegistration(codeStr);
        int type = 2, count1 = 0, count2 = 0;
        List <Integer> uids = new ArrayList <>();
        if (subjects != null) {
            if (subjects.contains("Written")) {
                type = 1;
            }
            //查询是否录入成绩
            //查看自己是否用这个账号录入录入
            count1 = artMapper.selectAchievementByRegAndUid(codeStr, uid, type);
            //查看这个报名号是不是已经全部录入了
            uids = artMapper.selectAchievementUidByReg(codeStr, type);
            count2 = uids.size();
        }
        if (student == null) {
            map.put("ok", false);
            map.put("message", "报名号有误");
        } else if (count1 >= 1 || count2 >= 2) {
            map.put("ok", false);
            map.put("message", "报名号:" + codeStr + "  成绩已录入");
        } else {
            //判断是不是自己所在的组(这个学生已经有一个登分员登了，并且已经登的那个组和自己的组一样)
            if (count2 == 1) {
                User user = artMapper.findGroupByUid(Integer.parseInt(uid));
                User oldUser = artMapper.findGroupByUid(uids.get(0));

                //如果两个的组不相同
                if (oldUser.getGroup() != user.getGroup()) {
                    map.put("ok", false);
                    map.put("message", "该考生是第" + oldUser.getGroup() + "组录的");
                    return JSONObject.toJSON(map);
                }else if ( oldUser.getSerial() == user.getSerial() ){
                    //分组不正确
                    map.put("ok",false);
                    map.put("message","报名号:" + codeStr + "  成绩已录入");
                    return  map;
                }
            }
            map.put("name", student.getName());
            map.put("studentSid", student.getSid());
            map.put("state", 0);
            map.put("ok", true);
            map.put("url", "/" + subjects);
        }
        return JSONObject.toJSON(map);
    }
    public Object reviewScore(String codeStr) {
        int type = 2;
        Map <String, Object> map = new HashMap <>();
        //查询所属专业
        String subjects = artMapper.SelectSubjects(codeStr);
        //查询学生信息
        Student student = artMapper.selectStudentByRegistration(codeStr);
        //查询学生信息
        if (subjects.contains( "Written" ))
            type = 1;

        Achievement achievement = artMapper.findReviewScoreBySidAndType(student.getSid(), type);
        if (achievement == null) {
            map.put("ok", false);
            map.put("message", "考试编号有误");
        } else {
            map.put("registration", student.getRegistration());
            map.put("name", student.getName());
            map.put("studentSid", student.getSid());
            map.put("achievements", achievement.getAchievements());
            map.put("state", 1);
            map.put("ok", true);
            map.put("url", "/" + subjects);
        }
        System.out.print( achievement + "\r\n");
        return JSONObject.toJSON(map);
    }
    @ResponseBody
    @RequestMapping(value = "/choiceScore", produces = "application/json;charset=UTF-8")
    public Object choiceScore(HttpServletRequest request) {
        final String[] subList = {"radioDirector", "televisionLiterature", "broadCasting", "aviationService"};
        final String[] type = {"Written", "Interview"};
        String aid = request.getParameter("aid");
        System.out.println("codeStr:" + aid);
        Map <String, Object> map = new HashMap <>();
        //查询学生信息
        Achievement achievement = artMapper.findAchievementByAid(aid);
        if (achievement == null) {
            map.put("ok", false);
            map.put("message", "考试编号有误");
        } else {
            Student student = artMapper.selectStudentBySid(achievement.getSid());
            String subjects;
            int id = artMapper.findSubjectId(student.getRegistration());
            if (id == 1 || id == 2) {
                subjects = subList[id - 1] + "" + type[achievement.getType() - 1];
            } else {
                subjects = subList[id - 1];
            }
            String achievements2 = artMapper.findOtherAchievements(aid);
            System.out.println("ach2:" + achievements2);
            map.put("registration", student.getRegistration());
            map.put("name", student.getName());
            map.put("studentSid", student.getSid());
            map.put("achievements", achievement.getAchievements());
            map.put("achievements2", achievements2);
            map.put("ok", true);
            map.put("url", "/" + subjects);
        }
        return JSONObject.toJSON(map);
    }

    @ResponseBody
    @RequestMapping(value = "/submitAchievement", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public Object submitAchievement(Achievement achievement, Boolean admin) {
        System.out.println(achievement);
        System.out.println("admin:" + admin);
        Map <String, Object> map = new HashMap <>();
        byte state = 0;
        int res = 1;
        List <Achievement> achievements = artMapper.findAllAchievementBySid(achievement.getSid(), achievement.getType());
        System.out.println("start");
        for (Achievement a : achievements) {
            System.out.println(a);
        }
        int lenght = achievements.size();

        if (admin != null && admin) {
            state = 3;
            achievement.setComment("管理员：" + achievement.getUid());
            for (Achievement a : achievements) {
                //管理员处理异常数据
                artMapper.setAchievementState(a.getAid(), 2);
            }
        } else {
            if (lenght == 1) {
                //数据库判断是否重复提交
                if (achievement.getUid()==achievements.get(0).getUid()){
                    map.put("ok",false);
                    map.put("message","不能重复提交！");
                    return  map;
                }

                if ((!achievements.get(lenght - 1).getAchievements().equals(achievement.getAchievements()))
                        && (achievements.get(lenght - 1).getType() == achievement.getType())) {
                    state = 1;//第二条录入时检测数据不同，置两条数据为异常数据
                    res &= artMapper.setAchievementState(achievements.get(lenght - 1).getAid(),1);
                } else {
                    state = 2;
                    achievements.get(0).setState((byte) 3);
                    achievements.get(0).setComment(achievements.get(0).getUid() + "+" + achievement.getUid());
                    res &= artMapper.insertAchievement(achievements.get(0));
                    res &= artMapper.setAchievementState(achievements.get(0).getAid(),2);
                }
            }
        }
        achievement.setState(state);
        res &= artMapper.insertAchievement(achievement);
        map.put("ok", res);
        map.put("message",(res==1)?"提交成功":"提交失败");
        return JSONObject.toJSON(map);
    }

    @ResponseBody
    @RequestMapping(value = "/setExamType", produces = "application/json;charset=UTF-8")
    public Object setExamType(HttpServletRequest request) {
        final int[] num = {Integer.parseInt(request.getParameter("radio")), Integer.parseInt(request.getParameter("theatre"))};
        final String[] name = {"radioDirector", "televisionLiterature"};
        final String[] type = {"Written", "Interview"};
        boolean res = true;
        for (int i = 0; i < 2; i++) {
            res &= artMapper.setExamType(name[i] + type[num[i]], i + 1);
        }
        Map <String, Object> map = new HashMap <>();
        map.put("ok", res);
        return JSONObject.toJSON(map);
    }

    @ResponseBody
    @RequestMapping(value = "/getAbnormal", produces = "application/json;charset=UTF-8")
    public Object getAbnormal(int page, int limit) {
        Map <String, Object> map = new HashMap <>();
        List <Abnormal> achievements = artMapper.findAllAbnormalAchievement((page - 1) * limit, limit);
        int count = artMapper.findAllAbnormalAchievementCount();
        map.put("data", achievements);
        map.put("count", count);
        map.put("code", 0);
        return JSONObject.toJSON(map);
    }

    @ResponseBody
    @RequestMapping(value = "/selectAllScore", produces = "application/json;charset=UTF-8")
    public Object selectAllScore(int page, int limit) {
        Map <String, Object> map = new HashMap <>();
        List <Score> list = artMapper.selectAllScore((page - 1) * limit, limit);
        int count = artMapper.selectAllScoreCount();
        map.put("data", list);
        map.put("count", count);
        map.put("code", 0);
        return JSONObject.toJSON(map);
    }

    @ResponseBody
    @RequestMapping(value = "/findSingleAchievement", produces = "application/json;charset=UTF-8")
    public Object findSingleAchievement(int page, int limit) {
        Map <String, Object> map = new HashMap <>();
        List <Abnormal> list = artMapper.findSingleAchievement((page - 1) * limit, limit);
        int count = artMapper.findSingleAchievementCount();
        map.put("data", list);
        map.put("count", count);
        map.put("code", 0);
        return JSONObject.toJSON(map);
    }

    @RequestMapping("/index")
    public String index() {
        System.out.println("======================index");
        return "/index";
    }

    @RequestMapping("/home")
    public String home() {
        System.out.println("======================home");
        return "/user/home";
    }

    @RequestMapping("/admin")
    public String admin() {
        System.out.println("======================admin");
        return "/admin/home";
    }

    @RequestMapping("/administrator")
    public String administrator() {
        System.out.println("======================administrator");
        return "/admin/administrator";
    }

    @RequestMapping("/welcome")
    public String welcome() {
        System.out.println("======================welcome");
        return "/user/welcome";
    }

    @RequestMapping("/broadCasting")
    public String broadCasting() {
        System.out.println("======================broadCasting");
        return "/user/broadCasting";
    }

    @RequestMapping("/aviationService")
    public String aviationService() {
        System.out.println("======================aviationService");
        return "/user/aviationService";
    }

    @RequestMapping("/radioDirectorInterview")
    public String radioDirectorInterview() {
        System.out.println("广播电视编导-面试======================radioDirectorInterview");
        return "/user/radioDirectorInterview";
    }

    @RequestMapping("/radioDirectorWritten")
    public String radioDirectorWritten() {
        System.out.println("广播电视变编导-笔试======================radioDirectorWritten");
        return "/user/radioDirectorWritten";
    }

    @RequestMapping("/televisionLiteratureInterview")
    public String televisionLiteratureInterview() {
        System.out.println("戏剧影视文学-面试======================televisionLiteratureInterview");
        return "/user/televisionLiteratureInterview";
    }

    @RequestMapping("/televisionLiteratureWritten")
    public String televisionLiteratureWritten() {
        System.out.println("戏剧影视文学-笔试======================televisionLiteratureWritten");
        return "/user/televisionLiteratureWritten";
    }
}
